package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Producent;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class ProducentsDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    /*
     * Zwraca wszystkich producentow
     */
    public List<Producent> getAllProducents()
    {
        Session session = sessionFactory.openSession();

        List<Producent> producents = session.createCriteria(Producent.class)
                .list();

        session.close();

        return producents;
    }

    public Producent addProducent(String name)
    {
        Producent producent = new Producent();
        producent.setName(name);

        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(producent);

        tx.commit();
        session.close();

        return producent;
    }

    public Producent editProducent(Integer id, Producent producent) throws ItemNotFoundException
    {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Producent producentToEdit = (Producent) session.get(Producent.class, id);

        if(producentToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        producentToEdit.setName(producent.getName());
        session.update(producentToEdit);
        tx.commit();
        session.close();

        return producentToEdit;
    }

    public void deleteProducent(Integer id) throws ItemNotFoundException
    {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Producent where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
